package com.cg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cg.dto.AddLikeDTO;
import com.cg.dto.AddNewsDTO;
import com.cg.dto.UpdateNewsDTO;
import com.cg.entity.News;
import com.cg.entity.UserLike;
import com.cg.mapper.NewsMapper;
import com.cg.result.R;
import com.cg.service.AccountService;
import com.cg.service.ILikeService;
import com.cg.service.INewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 加
 * @since 2025-01-17
 */
@Service
public class NewsServiceImpl extends ServiceImpl<NewsMapper, News> implements INewsService {
    @Autowired
    private AccountService accountService;
    @Autowired
    private  INewsService newsService;
    @Autowired
    private ILikeService likeService;
    @Override
    public R addLike(AddLikeDTO addLikeDTO) {
        UserLike like=new UserLike();
        like.setNewsId(addLikeDTO.getNewsId());
        like.setUserId(accountService.getCurrentUserId());
        like.setContent(newsService.selectContentById(addLikeDTO.getNewsId()));
        likeService.save(like);
        return R.Success("收藏新闻成功");
    }

    @Override
    public R addNews(AddNewsDTO addNewsDTO) {
        News news=new News();
        BeanUtils.copyProperties(addNewsDTO,news);
        save(news);
        return  R.Success("新增新闻成功");
    }

    @Override
    public R deleteNews(Long newsId) {
        if(newsService.selectContentById(newsId)!=null&&newsId!=null) {
            News news = getById(newsId);
            removeById(news);
            return R.Success("删除成功");
        }else{
            return  R.Failed("删除失败，该新闻不存在");
        }
    }

    @Override
    public R updateNews(UpdateNewsDTO updateNewsDTO) {
        if(newsService.selectContentById(updateNewsDTO.getNewsId())!=null&&updateNewsDTO.getNewsId()!=null) {
            News news = getById(updateNewsDTO.getNewsId());
            BeanUtils.copyProperties(updateNewsDTO, news);
            updateById(news);
            return R.Success("修改成功");
        }else{
            return R.Failed("修改失败，该新闻不存在");
        }
    }

    @Override
    public String selectContentById(Long newsId) {
        News news=getById(newsId);
        if(news!=null) {
            return news.getTitle();
        }else{
            return null;
        }
    }
    @Override
    public R<List<News>> showNews() {
        LambdaQueryWrapper<News> queryWrapper=new LambdaQueryWrapper<>();
        List<News> list=list(queryWrapper);
        return R.Success(list);
    }
}
